package cn.lwj.controller;


import ch.qos.logback.core.pattern.color.BoldYellowCompositeConverter;
import cn.lwj.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${upload.path}")
    String path;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){

        // file 是一个临时文件 如果不转存 关闭服务器文件就会消失
        log.info(file.toString());
//        拿到原始的文件名
        String originalFilename = file.getOriginalFilename();
//        截取原始文件名的后缀
        String fileSuffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
//        使用UUID对象生成一个文件名前缀  防止原始文件名重复 覆盖之前的文件
        String fileName = UUID.randomUUID().toString() + fileSuffixName;

//        由于springboot配置的目录有可能不存在 所以需要进行一个判断
        File directory = new File(path);
        if(!directory.exists()){
            directory.mkdir();
        }
        try {
//            使用transferTo方法将文件转存至指定目录
//            采用springboot配置的方式和UUID的方式实现动态的存储和命名
            file.transferTo(new File(path + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);
    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //        创建服务器文件字节流  读取数据
            FileInputStream fileInputStream = new FileInputStream(new File(path + name));
            //        response 对象向浏览器响应数据
            ServletOutputStream outputStream = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ( (len = fileInputStream.read(bytes)) != -1 ){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }





}
